package com.itheima.controller;


import com.itheima.Service.UserService;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/api")
public class LoginAndRegController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     * @param user 包含用户名和密码的用户对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录: {}", user.getUsername());
        LoginInfo loginInfo = userService.login(user);
        if (loginInfo != null) {
            return Result.success(loginInfo);
        }
        return Result.error("用户名或密码错误");
    }

    /**
     * 用户注册接口
     * @param user 包含注册信息的用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        log.info("用户注册: {}", user.getUsername());

        // 基本参数校验
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }

        boolean success = userService.register(user);
        if (success) {
            return Result.success("注册成功");
        } else {
            return Result.error("注册失败，用户名已存在");
        }
    }
}
